//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Collections;
using CommunityServer.Components;

namespace CommunityServer.Discussions.Components
{
	/// <summary>
	/// Summary description for ForumRssHandler.
	/// </summary>
	public class ForumRssHandler : BaseForumSyndicationHandler
	{
		public ForumRssHandler()
		{
		}

        protected  ThreadViewMode mode = ThreadViewMode.Default;
		protected bool threadless = false;

	    /// <summary>
	    /// The key used to lookup the feed uniquely in the cache.
	    /// </summary>
	    /// <returns></returns>
	    protected override string CacheKey
	    {
			get { return string.Format("ForumRss:{0}:Post:{2}:Mode{1}:Threadless:{3}", CSContext.Current.SectionID.ToString(), mode, CSContext.Current.PostID, threadless.ToString()); }
		}


		protected override void ProcessFeed()
        {
            CSContext csContext = CSContext.Current;

            if(!ForumConfig.EnableForumsRSS)
            {
                 Context.Response.Write("Error - RSS Is Not Enabled.");
                return;
            }

            // Do we have a mode argument?
            if (csContext.Context.Request.QueryString["mode"] != null) 
            {
                mode = (ThreadViewMode) int.Parse(csContext.Context.Request.QueryString["mode"]);
            }

			// Do we have a threadless argument?
			if (csContext.Context.Request.QueryString["threadless"] != null) 
			{
				if (int.Parse(csContext.Context.Request.QueryString["threadless"]) == 1)
					threadless = true;
			}
			
			if(csContext.SectionID <= 0)
            {
                Globals.Return404(Context);
            }

            base.ProcessFeed ();
        }


	    /// <summary>
	    /// Builds the actual feed.
	    /// </summary>
	    /// <returns>The cached feed.</returns>
	    protected override CachedFeed BuildFeed()
	    {
            CSContext cntx = CSContext.Current;
			ArrayList posts = null;

            ForumThreadQuery query = new ForumThreadQuery();
            query.ForumID = GetCurrentSection.SectionID;
			query.PageSize = ForumConfig.RssDefaultThreadsPerFeed;
			query.SortBy = SortThreadsBy.LastPost;
			query.Order = SortOrder.Descending;

            // Don't sort by StickyDate for RSS feeds, otherwise the most recent post date won't be correct
            query.IgnoreStickyPosts = true;

	    	if (this.threadless)
			{
				posts = Posts.GetPosts_RSSThreadless(cntx.SectionID, 15).Posts;
			}
			else
			{

				switch (mode) 
				{
					case ThreadViewMode.Active:
						query.ActiveTopics = true;
						query.UnAnsweredOnly = true;
						posts = Threads.GetThreads(query).Threads;
						break;

					case ThreadViewMode.Unanswered:
						query.UnAnsweredOnly = true;
						posts = Threads.GetThreads(query).Threads;
						break;

					default:
						if(cntx.PostID != -1)
							posts = Posts.GetPosts(cntx.PostID, 0, 15, 0, 1).Posts;
						else
							posts = Threads.GetThreads(query).Threads;
						break;
				}

			}
			
            ForumRssWriter writer = new ForumRssWriter(posts, GetCurrentSection, this.BaseUrl);

            DateTime dt =  posts.Count > 0 ? ((Post)posts[0]).PostDate : DateTime.Now;
            
            return new CachedFeed(dt, null, writer.GetXml());
	    }

      
	}
}
